﻿using Autofac;
using EventBus.RabbitMQ.Events;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;

namespace EventBus.RabbitMQ
{
    /// <summary>
    /// 
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        public static List<Type> HandlerTypeList = new List<Type>();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configure"></param>
        /// <returns></returns>
        public static IServiceCollection ConfigRabbitMqBus(this IServiceCollection services, Action<RabbitMqOptions> configure)
        {
            services.Configure(configure);
            return services;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static ContainerBuilder RegisterRabbitMqBus(this ContainerBuilder builder)
        {
            if (builder == null)
                throw new ArgumentNullException(nameof(builder));
            builder.RegisterType<ConnectionChannelPool>().As(typeof(IConnectionChannelPool)).SingleInstance().PropertiesAutowired();
            builder.RegisterType<RabbitMqBus>().As(typeof(IQueueBus)).SingleInstance().PropertiesAutowired();
            builder.RegisterType<RabbitMqConsumerClientFactory>().As(typeof(IConsumerClientFactory)).SingleInstance().PropertiesAutowired();
            builder.RegisterType<ConsumerServiceSelector>().As(typeof(IConsumerServiceSelector)).SingleInstance().PropertiesAutowired();
            builder.RegisterType<ConsumerRegister>().As(typeof(IConsumerRegister)).SingleInstance().PropertiesAutowired();
            return builder;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static ContainerBuilder RegisterBusHandler<T>(this ContainerBuilder builder) where T : IQueueHandler
        {
            var type = typeof(T);
            HandlerTypeList.Add(type);
            builder.RegisterType<T>().InstancePerDependency().PropertiesAutowired();
            return builder;
        }
    }
}